package cn.netswap.jeegorilla.framework.security.social.weixin;

import cn.netswap.jeegorilla.framework.security.social.weixin.providerinfo.WeiXin;
import cn.netswap.jeegorilla.framework.security.social.weixin.providerinfo.WeiXinAccessGrant;
import cn.netswap.jeegorilla.framework.security.social.weixin.providerinfo.WeiXinAdapter;
import cn.netswap.jeegorilla.framework.security.social.weixin.providerinfo.WeiXinServiceProvider;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

/**
 * @author lgw
 * @version 1.0
 * @date 2020/3/24 11:53
 */
public class WeiXinConnectionFactory extends OAuth2ConnectionFactory<WeiXin> {
    public WeiXinConnectionFactory(String providerId, String appId, String appSecret) {
        super(providerId, new WeiXinServiceProvider(appId, appSecret), new WeiXinAdapter());
    }

    @Override
    protected String extractProviderUserId(AccessGrant accessGrant) {
        if (accessGrant instanceof WeiXinAccessGrant) {
            return ((WeiXinAccessGrant)accessGrant).getOpenId();
        }

        return null;
    }

    @Override
    public Connection<WeiXin> createConnection(AccessGrant accessGrant) {

        return new OAuth2Connection<WeiXin>(getProviderId(), extractProviderUserId(accessGrant), accessGrant.getAccessToken(),
                accessGrant.getRefreshToken(), accessGrant.getExpireTime(), getOAuth2ServiceProvider(), getApiAdapter());
    }


    public OAuth2ServiceProvider<WeiXin> getOAuth2ServiceProvider() {
        return (OAuth2ServiceProvider<WeiXin>) getServiceProvider();
    }

    protected ApiAdapter<WeiXin> getApiAdapter(String providerUserId) {
        return new WeiXinAdapter(providerUserId);
    }

}
